package com.yy.base.servlet.upload;

import com.yy.base.util.UserUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;

public class DownFileServlet extends HttpServlet {
	private static final long serialVersionUID = 7618658514199005769L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			HttpSession session = request.getSession(false);
			if (session.getAttribute(UserUtil.USERSESSION) == null) {
				response.sendError(404, "no login!");
				return;
			}
			String filePath = request.getParameter("filePath");
			String onLine = request.getParameter("onLine");
			String fileName = request.getParameter("fileName");
			if (fileName == null) {
				fileName = "filename";
			}
			downLoad(filePath, response, fileName, "true".equalsIgnoreCase(onLine));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    /**
	 * 下载
	 * @param filePath 文件路径
	 * @param isOnLine 是否在线打开
	 */
	public void downLoad(String filePath, HttpServletResponse response, String fileName, boolean isOnLine) throws Exception {
		File f = new File(filePath);
		if (!f.exists()) {
			response.sendError(404, "File not found!");
			return;
		}
		BufferedInputStream br = null;
		OutputStream out = null;
		try {
			br = new BufferedInputStream(new FileInputStream(f));
			String name = new String(fileName.getBytes("GBK"), "iso8859-1"); // 修改编码
			byte[] buf = new byte[1024];
			int len = 0;
			response.reset(); // 非常重要
			if (isOnLine) { // 在线打开方式
				URL u = new URL("file:///" + filePath);
				response.setContentType(u.openConnection().getContentType());
				response.setHeader("Content-Disposition", "inline; filename=" + name);
				// 文件名应该编码成UTF-8
			} else { // 纯下载方式
				response.setContentType("application/x-msdownload");
				response.setHeader("Content-Disposition", "attachment; filename=" + name);
			}
			out = response.getOutputStream();
			while ((len = br.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
		} catch (Exception e) {
			System.out.println("下载文件失败!" + "--" + filePath);
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch (Exception ex) {
			}
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception ex) {
			}
		}
	}
}